#include "sendfile.h"

#include <QFile>
#include <QHostAddress>
#include <QFileInfo>

SendFile::SendFile(QObject *parent) : QObject(parent)
{

}

void SendFile::ConnectServer(QString ip, unsigned short port)
{
    m_tcp = new QTcpSocket;
    m_tcp->connectToHost(QHostAddress(ip), port);
    // 因为connectToHost是非阻塞函数，所以不能通过返回值来判断是否连接成功，需要根据信号判断:
    connect(m_tcp,&QTcpSocket::connected, this,&SendFile::connectOK);

    // 判断断开连接
    connect(m_tcp,&QTcpSocket::disconnected, this,[=](){
        m_tcp->close();

        // to do释放
        emit gameOver();
    });
}

void SendFile::sendFile(QString path)
{
    QFile file(path);
    QFileInfo info(path);
    int fileSize = info.size();
    int num = 0;

    file.open(QFile::ReadOnly);

    QByteArray line;
    while(!file.atEnd())
    {
        if(num == 0)
        {
            m_tcp->write((char*)&fileSize,4);
        }
        line = file.readLine();
        num += line.size();
        int percent = (num * 100 / fileSize);
        emit curPercent(percent);

        m_tcp->write(line);
    }


}
